package edu.swu.pp.util;

import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.Random;

import javax.imageio.ImageIO;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Servlet implementation class AuthCode
 * 用于生成图形验证码的Servlet
 * 基本思路是先随即产生几个数字，然后在内存中画出来，再加上一些扰乱线，有的甚至还加入了变形，
 * 然后输出到页面。在产生随即数的同时，还将这个随机数字保存到session，以供后面判断
 */
public class AuthCode extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public AuthCode() {
        super();
        // TODO Auto-generated constructor stub
    }
	
	@Override
	protected void service(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		//设置响应消息头
		response.setHeader("Pragma", "No-cache");
		response.setHeader("Cache-Control", "no-cache");
		response.setHeader("Expires", "0");
		
		int i_width = 60;
		int i_height = 20;
		BufferedImage image = new BufferedImage(i_width, i_height, BufferedImage.TYPE_INT_BGR);
		
		Graphics g = image.getGraphics();
		       
		Random random = new Random();
		    
		g.setColor(getRandColor(200, 250));
	    g.fillRect(0, 0, i_width, i_height);
	
		g.setFont(new Font("Times New Roman", Font.PLAIN, 18));
		g.setColor(getRandColor(160, 200));
		
		for(int i = 0 ; i < 155; i++) {
			int i_x = random.nextInt(i_width);
			int i_y = random.nextInt(i_height);
			int i_x1 = random.nextInt(12);
			int i_y1 = random.nextInt(12);
			g.drawLine(i_x, i_y, i_x1, i_y1);
		}
		
		String authCode = "";
		for(int i = 0 ; i < 4 ; i++) {
		String randChar = String.valueOf(random.nextInt(10));
		  	authCode += randChar;
		       
		     g.setColor(new Color(20+random.nextInt(110), 20+random.nextInt(110), 20+random.nextInt(110)));
		     g.drawString(randChar, 13*i+6, 16);
		}
		     
		request.getSession().setAttribute("authCode", authCode);
		        
		System.out.println("验证码是" + authCode);
		       
		g.dispose();
		       
		ImageIO.write(image, "JPEG", response.getOutputStream());
	}

	/**
	 * 随机获取颜色
	 * @param fc
	 * @param bc
	 * @return
	 */
	private Color getRandColor(int fc, int bc) {
		Random random = new Random();
		if(fc > 255) fc = 255;
		if(bc > 255) bc = 255;
		int r = fc + random.nextInt(bc - fc);
		int g = fc + random.nextInt(bc - fc);
		int b = fc + random.nextInt(bc - fc);
		return new Color(r,g,b);
	}

}
